#include "erdiagramview.h"
#include <QGraphicsScene>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QSqlRecord>
#include <QSqlField>
#include <QGraphicsRectItem>
#include <QGraphicsTextItem>
#include <QGraphicsLineItem>
#include <QWheelEvent>
#include <QScrollBar>
#include <QBrush>
#include <QPen>
#include <QColor>
#include <QFont>
#include <QApplication>
#include <QMessageBox>
#include <QMap>
#include <QVector>

// 表示一个表的图形项
class TableItem : public QGraphicsRectItem
{
public:
    TableItem(const QString &name, const QStringList &columns, QGraphicsItem *parent = nullptr)
        : QGraphicsRectItem(parent)
        , m_name(name)
    {
        setFlags(QGraphicsItem::ItemIsSelectable | QGraphicsItem::ItemIsMovable);
        setBrush(QBrush(QColor(240, 240, 255)));
        setPen(QPen(QColor(100, 100, 200), 2));
        
        // 表名
        QGraphicsTextItem *nameItem = new QGraphicsTextItem(name, this);
        QFont nameFont = nameItem->font();
        nameFont.setBold(true);
        nameItem->setFont(nameFont);
        nameItem->setPos(5, 5);
        
        // 列信息
        qreal yPos = 25;
        for (const QString &column : columns) {
            QGraphicsTextItem *columnItem = new QGraphicsTextItem(column, this);
            columnItem->setPos(5, yPos);
            yPos += 15;
        }
        
        // 设置矩形大小
        qreal width = 200;
        qreal height = qMax(yPos + 10, 60.0);
        setRect(0, 0, width, height);
    }
    
private:
    QString m_name;
};

ERDiagramView::ERDiagramView(QWidget *parent)
    : QGraphicsView(parent)
    , m_scene(nullptr)
    , m_currentScale(1.0)
{
    setupUI();
}

void ERDiagramView::setDatabase(const QSqlDatabase &db)
{
    m_database = db;
}

void ERDiagramView::refreshDiagram()
{
    if (!m_database.isOpen()) {
        return;
    }
    
    clearDiagram();
    loadDatabaseSchema();
}

void ERDiagramView::zoomIn()
{
    if (m_currentScale < MAX_SCALE) {
        m_currentScale *= SCALE_FACTOR;
        m_scene->setScale(m_currentScale);
    }
}

void ERDiagramView::zoomOut()
{
    if (m_currentScale > MIN_SCALE) {
        m_currentScale /= SCALE_FACTOR;
        m_scene->setScale(m_currentScale);
    }
}

void ERDiagramView::zoomReset()
{
    m_currentScale = 1.0;
    m_scene->setScale(m_currentScale);
}

void ERDiagramView::setupUI()
{
    m_scene = new QGraphicsScene(this);
    setScene(m_scene);
    
    // 设置视图属性
    setRenderHint(QPainter::Antialiasing);
    setDragMode(QGraphicsView::ScrollHandDrag);
    setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
    setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
    
    // 隐藏滚动条
    setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
}

void ERDiagramView::loadDatabaseSchema()
{
    if (!m_database.isOpen()) {
        return;
    }
    
    // 获取所有表
    QStringList tables = m_database.tables();
    
    // 存储表项的位置
    QMap<QString, TableItem*> tableItems;
    qreal xPos = 50;
    qreal yPos = 50;
    const qreal xSpacing = 250;
    const qreal ySpacing = 200;
    int col = 0;
    int row = 0;
    
    // 为每个表创建图形项
    for (const QString &tableName : tables) {
        // 获取表的列信息
        QSqlRecord record = m_database.record(tableName);
        QStringList columns;
        for (int i = 0; i < record.count(); ++i) {
            QSqlField field = record.field(i);
            QString columnInfo = QString("%1 (%2)").arg(field.name()).arg(field.typeID());
            columns.append(columnInfo);
        }
        
        // 创建表项
        TableItem *tableItem = new TableItem(tableName, columns);
        tableItems[tableName] = tableItem;
        
        // 设置位置
        tableItem->setPos(xPos + col * xSpacing, yPos + row * ySpacing);
        m_scene->addItem(tableItem);
        
        col++;
        if (col > 3) { // 每行最多4个表
            col = 0;
            row++;
        }
    }
    
    // TODO: 添加表之间的关系线（外键关系）
    // 这需要查询表的外键信息，不同数据库的查询方式不同
    
    // 调整场景大小
    m_scene->setSceneRect(m_scene->itemsBoundingRect());
}

void ERDiagramView::clearDiagram()
{
    m_scene->clear();
}

// 鼠标滚轮缩放
void ERDiagramView::wheelEvent(QWheelEvent *event)
{
    if (event->modifiers() & Qt::ControlModifier) {
        // Ctrl+滚轮进行缩放
        if (event->angleDelta().y() > 0) {
            zoomIn();
        } else {
            zoomOut();
        }
        event->accept();
    } else {
        // 默认滚动行为
        QGraphicsView::wheelEvent(event);
    }
}